<template>
    <!-- 非全屏容器（常驻） -->

    <div
        v-if="!isFullScreen"
        class="h-[calc(100vh-90px)] w-full flex flex-col overflow-hidden rounded-2xl json-converter-container"
    >
        <!-- 主内容区域：左右两个框 -->
        <div class="flex-1 flex overflow-hidden" ref="containerRef">
            <!-- 左侧输入框 -->
            <div class="json-converter-panel flex flex-col" :style="{ flex: `0 0 ${leftWidth}%` }">
                <div class="json-converter-panel-header px-4 py-2 flex items-center justify-between">
                    <div class="json-converter-panel-header-title text-sm font-medium">输入 JSON</div>
                    <span class="json-converter-panel-header-subtitle text-xs">{{ inputJson.length }} 字符</span>
                </div>
                <div class="json-converter-panel-body flex-1 p-4">
                    <textarea
                        v-model="inputJson"
                        class="json-converter-input w-full h-full resize-none bg-transparent font-mono !text-lg leading-relaxed outline-none border-none"
                        placeholder="请输入需要转换的JSON数据..."
                        spellcheck="false"
                    />
                </div>
            </div>

            <!-- 可拖动分隔条 -->
            <div
                class="json-converter-resizer relative w-[6px] cursor-col-resize select-none bg-transparent"
                @mousedown="startDragging"
                title="拖动调整左右宽度"
            >
                <div class="json-converter-resizer-line absolute inset-y-0 left-1/2 -translate-x-1/2 w-px"></div>
            </div>

            <!-- 右侧结果框 -->
            <div class="json-converter-panel flex-1 flex flex-col min-w-0">
                <div class="json-converter-panel-header px-4 py-2 flex items-center justify-between">
                    <div class="json-converter-panel-header-title text-sm font-medium">转换结果</div>

                    <div class="json-converter-actions flex items-center gap-3">
                        <span class="json-converter-panel-header-subtitle text-xs">{{ outputJson.length }} 字符</span>
                        <a
                            class="json-converter-actions-item flex items-center cursor-pointer"
                            title="复制"
                            @click="copyOutput"
                        >
                            <CopyOutlined class="text-sm" />
                        </a>
                        <a
                            class="json-converter-actions-item flex items-center cursor-pointer"
                            title="全屏"
                            @click="handleFullScreen"
                        >
                            <FullscreenOutlined class="text-sm" />
                        </a>
                    </div>
                </div>
                <div class="json-converter-viewer flex-1 overflow-y-auto">
                    <!-- 结构化视图 -->
                    <div class="h-full">
                        <JsonViewer :model-value="outputJson" />
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 全屏容器（使用过渡进入/离开） -->
    <Transition name="fs">
        <div
            v-if="isFullScreen"
            class="json-converter-fullscreen fixed left-0 top-0 w-[100vw] h-[100vh] flex flex-col overflow-hidden rounded-none z-999"
        >
            <div class="flex-1 flex overflow-hidden" ref="containerRef">
                <!-- 左侧输入框 -->
                <div class="json-converter-panel flex flex-col" :style="{ flex: `0 0 ${leftWidth}%` }">
                    <div class="json-converter-panel-header px-4 py-2 flex items-center justify-between">
                        <div class="json-converter-panel-header-title text-sm font-medium">输入 JSON</div>
                        <span class="json-converter-panel-header-subtitle text-xs">{{ inputJson.length }} 字符</span>
                    </div>
                    <div class="json-converter-panel-body flex-1 p-4">
                        <textarea
                            v-model="inputJson"
                            class="json-converter-input w-full h-full resize-none bg-transparent font-mono !text-lg leading-relaxed outline-none border-none"
                            placeholder="请输入需要转换的JSON数据..."
                            spellcheck="false"
                        />
                    </div>
                </div>

                <!-- 可拖动分隔条 -->
                <div
                    class="json-converter-resizer relative w-[6px] cursor-col-resize select-none bg-transparent"
                    @mousedown="startDragging"
                    title="拖动调整左右宽度"
                >
                    <div class="json-converter-resizer-line absolute inset-y-0 left-1/2 -translate-x-1/2 w-px"></div>
                </div>

                <!-- 右侧结果框 -->
                <div class="json-converter-panel flex-1 flex flex-col min-w-0">
                    <div class="json-converter-panel-header px-4 py-2 flex items-center justify-between">
                        <div class="json-converter-panel-header-title text-sm font-medium">转换结果</div>

                        <div class="json-converter-actions flex items-center gap-3">
                            <span class="json-converter-panel-header-subtitle text-xs"
                                >{{ outputJson.length }} 字符</span
                            >
                            <a
                                class="json-converter-actions-item flex items-center cursor-pointer"
                                title="复制"
                                @click="copyOutput"
                            >
                                <CopyOutlined class="text-sm" />
                            </a>
                            <a
                                class="json-converter-actions-item flex items-center cursor-pointer"
                                title="退出全屏"
                                @click="handleFullScreen"
                            >
                                <FullscreenExitOutlined class="text-sm" />
                            </a>
                        </div>
                    </div>
                    <div class="json-converter-viewer flex-1 overflow-y-auto">
                        <!-- 结构化视图 -->
                        <div class="h-full">
                            <JsonViewer :model-value="outputJson" />
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </Transition>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { JsonViewer } from './components'
import { CopyOutlined, FullscreenOutlined, FullscreenExitOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
// import { onBeforeRouteLeave } from 'vue-router'

// 响应式数据
const inputJson = ref('')
const outputJson = ref('')
const isFullScreen = ref<boolean>(false)
// 左侧宽度百分比
const leftWidth = ref<number>(20)
// 拖拽控制
const isDragging = ref<boolean>(false)
const containerRef = ref<HTMLElement | null>(null)

// JSON反转义
const unescapeJson = () => {
    try {
        const unescaped = JSON.parse(inputJson.value)
        if (typeof unescaped === 'string') {
            // 尝试再次解析，看是否是JSON字符串
            try {
                const parsed = JSON.parse(unescaped)
                outputJson.value = JSON.stringify(parsed, null, 2)
            } catch {
                outputJson.value = unescaped
            }
        } else {
            outputJson.value = JSON.stringify(unescaped, null, 2)
        }
    } catch {
        outputJson.value = '格式不正确...'
    }
}

// 复制输出结果
const copyOutput = async () => {
    try {
        await navigator.clipboard.writeText(outputJson.value)
        message.success('复制成功')
    } catch {
        // 如果浏览器不支持clipboard API，使用传统方法
        const textArea = document.createElement('textarea')
        textArea.value = outputJson.value
        document.body.appendChild(textArea)
        textArea.select()
        document.execCommand('copy')
        document.body.removeChild(textArea)
        message.success('复制成功')
    }
}
// 全屏切换
const handleFullScreen = () => {
    isFullScreen.value = !isFullScreen.value
}
// 开始拖拽分隔条
const startDragging = (e: MouseEvent) => {
    isDragging.value = true
    const onMouseMove = (ev: MouseEvent) => {
        if (!isDragging.value || !containerRef.value) return
        const rect = containerRef.value.getBoundingClientRect()
        const x = Math.min(Math.max(ev.clientX - rect.left, 0), rect.width)
        const percent = (x / rect.width) * 100
        leftWidth.value = Math.min(Math.max(percent, 20), 80)
    }
    const onMouseUp = () => {
        isDragging.value = false
        window.removeEventListener('mousemove', onMouseMove)
        window.removeEventListener('mouseup', onMouseUp)
    }
    window.addEventListener('mousemove', onMouseMove)
    window.addEventListener('mouseup', onMouseUp)
    e.preventDefault()
}
/** 离开页面时，提示是否离开 */
// onBeforeRouteLeave((to, from, next) => {
//   console.log(to, from);
//   next(false)
//   message.error('请先保存数据')
// })
watch(
    () => inputJson.value,
    () => {
        unescapeJson()
    },
)
</script>
<style lang="scss" scoped>
/* 进入/离开全屏时的过渡动画 */
.fs-enter-active,
.fs-leave-active {
    transition:
        opacity 0.25s ease,
        transform 0.25s ease,
        border-radius 0.25s ease;
}

.fs-enter-from,
.fs-leave-to {
    opacity: 0;
    transform: scale(0.98);
}
</style>
